<?php

namespace App\Ad\MediaApi;

use App\Commons\SingleInstanceTrait;

class MediaApiBase
{
    use SingleInstanceTrait;

    public function __construct()
    {
        //
    }

    // 获取授权回调链接
    public function getAuthRedirectUri()
    {
        $url = config('app.url') . '/media/media_auth';
        return urlencode($url);
    }

    public function curl($url, $params = [], $ispost = false, $https = false, $timeout = 30, $x_www_form = false, $header = [])
    {
        $httpInfo = array();
        $ch       = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // 是否使用https
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        }

        // 是否post模式
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_URL, $url);
            if ($x_www_form === true) {
                // 是否使用 x-www-form-urlencoded 提交
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            }
        } else {
            if (!empty($params)) {
                $params = http_build_query($params);
                curl_setopt($ch, CURLOPT_URL, $url . (stripos($url, '?') === false ? '?' : '&') . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $response  = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($response === false) {
            return [$http_code, false];
        }

        if ($http_code != 200) {
            return [$http_code, false];
        }

        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return [$http_code, $response];
    }
}
